package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysMessageMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.UserRelationMapper;
import com.ruoyi.system.domain.SysMessage;
import com.ruoyi.system.domain.UserRelation;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysMessageService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 消息通知Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysMessageServiceImpl implements ISysMessageService
{
    @Autowired
    private SysMessageMapper sysMessageMapper;
    
    @Autowired
    private UserRelationMapper userRelationMapper;
    
    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询消息通知
     * 
     * @param messageId 消息通知主键
     * @return 消息通知
     */
    @Override
    public SysMessage selectSysMessageByMessageId(Long messageId)
    {
        return sysMessageMapper.selectSysMessageByMessageId(messageId);
    }

    /**
     * 查询消息通知列表
     * 
     * @param sysMessage 消息通知
     * @return 消息通知
     */
    @Override
    public List<SysMessage> selectSysMessageList(SysMessage sysMessage)
    {
        return sysMessageMapper.selectSysMessageList(sysMessage);
    }

    /**
     * 新增消息通知
     * 
     * @param sysMessage 消息通知
     * @return 结果
     */
    @Override
    public int insertSysMessage(SysMessage sysMessage)
    {
        sysMessage.setCreateTime(DateUtils.getNowDate());
        sysMessage.setSendTime(DateUtils.getNowDate());
        if (sysMessage.getStatus() == null) {
            sysMessage.setStatus("0");
        }
        if (sysMessage.getIsPush() == null) {
            sysMessage.setIsPush("0");
        }
        if (sysMessage.getDelFlag() == null) {
            sysMessage.setDelFlag("0");
        }
        return sysMessageMapper.insertSysMessage(sysMessage);
    }

    /**
     * 修改消息通知
     * 
     * @param sysMessage 消息通知
     * @return 结果
     */
    @Override
    public int updateSysMessage(SysMessage sysMessage)
    {
        return sysMessageMapper.updateSysMessage(sysMessage);
    }

    /**
     * 批量删除消息通知
     * 
     * @param messageIds 需要删除的消息通知主键
     * @return 结果
     */
    @Override
    public int deleteSysMessageByMessageIds(Long[] messageIds)
    {
        return sysMessageMapper.deleteSysMessageByMessageIds(messageIds);
    }

    /**
     * 删除消息通知信息
     * 
     * @param messageId 消息通知主键
     * @return 结果
     */
    @Override
    public int deleteSysMessageByMessageId(Long messageId)
    {
        return sysMessageMapper.deleteSysMessageByMessageId(messageId);
    }
    
    /**
     * 标记消息为已读
     * 
     * @param messageId 消息ID
     * @return 结果
     */
    @Override
    public int markAsRead(Long messageId)
    {
        return sysMessageMapper.markAsRead(messageId);
    }
    
    /**
     * 查询用户未读消息数量
     * 
     * @param userId 用户ID
     * @param userType 用户类型（1老人 2家属）
     * @return 结果
     */
    @Override
    public int getUnreadCount(Long userId, String userType)
    {
        return sysMessageMapper.selectUnreadCount(userId, userType);
    }
    
    /**
     * 发送余额不足提醒
     * 
     * @param user 用户信息
     * @param balance 当前余额
     * @return 结果
     */
    @Override
    public void sendBalanceReminder(SysUser user, Double balance)
    {
        if (user == null) {
            return;
        }
        
        // 发送给老人
        SysMessage elderMessage = new SysMessage();
        elderMessage.setTitle("账户余额不足提醒");
        elderMessage.setContent("尊敬的" + user.getNickName() + "，您的账户当前余额为" + balance + "元，已经不足，请及时充值以确保服务正常使用。");
        elderMessage.setMessageType("2");  // 余额提醒
        elderMessage.setReceiverId(user.getUserId());
        elderMessage.setReceiverType("1"); // 老人
        this.insertSysMessage(elderMessage);
        
        // 发送给家属
        UserRelation query = new UserRelation();
        query.setElderUserId(user.getUserId());
        query.setDelFlag("0"); // 确保只查询未删除的关系
        List<UserRelation> relations = userRelationMapper.selectUserRelationList(query);
        
        if (relations != null && !relations.isEmpty()) {
            for (UserRelation relation : relations) {
                SysUser familyUser = userMapper.selectUserById(relation.getFamilyUserId());
                if (familyUser != null) {
                    SysMessage familyMessage = new SysMessage();
                    familyMessage.setTitle("家人账户余额不足提醒");
                    familyMessage.setContent("尊敬的" + familyUser.getNickName() + "，您的家人" + user.getNickName() + "的账户当前余额为" + balance + "元，已经不足，请及时为其充值以确保服务正常使用。");
                    familyMessage.setMessageType("2");  // 余额提醒
                    familyMessage.setReceiverId(familyUser.getUserId());
                    familyMessage.setReceiverType("2"); // 家属
                    this.insertSysMessage(familyMessage);
                }
            }
        }
    }
    
    /**
     * 发送退住通知
     * 
     * @param elderUser 老人用户
     * @param bedName 床位名称
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, DuplicateKeyException.class})
    public void sendCheckOutNotification(SysUser elderUser, String bedName)
    {
        if (elderUser == null) {
            return;
        }
        
        // 发送给老人
        SysMessage elderMessage = new SysMessage();
        elderMessage.setTitle("退住通知");
        elderMessage.setContent("尊敬的" + elderUser.getNickName() + "，您已成功办理" + bedName + "的退住手续。如有任何问题，请联系工作人员。祝您生活愉快！");
        elderMessage.setMessageType("3");  // 退住通知
        elderMessage.setReceiverId(elderUser.getUserId());
        elderMessage.setReceiverType("1"); // 老人
        this.insertSysMessage(elderMessage);
        
        // 发送给家属
        UserRelation query = new UserRelation();
        query.setElderUserId(elderUser.getUserId());
        query.setDelFlag("0"); // 确保只查询未删除的关系
        List<UserRelation> relations = userRelationMapper.selectUserRelationList(query);
        
        if (relations != null && !relations.isEmpty()) {
            for (UserRelation relation : relations) {
                SysUser familyUser = userMapper.selectUserById(relation.getFamilyUserId());
                if (familyUser != null) {
                    SysMessage familyMessage = new SysMessage();
                    familyMessage.setTitle("家人退住通知");
                    familyMessage.setContent("尊敬的" + familyUser.getNickName() + "，您的家人" + elderUser.getNickName() + "已成功办理" + bedName + "的退住手续。如有任何问题，请联系工作人员。");
                    familyMessage.setMessageType("3");  // 退住通知
                    familyMessage.setReceiverId(familyUser.getUserId());
                    familyMessage.setReceiverType("2"); // 家属
                    this.insertSysMessage(familyMessage);
                }
            }
        }
    }
} 